package com.shiroha.notification.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class EmailApiClient {
    private final EmailProperties emailProperties;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    @Autowired
    public EmailApiClient(EmailProperties emailProperties, @Qualifier("restTemplate") RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.emailProperties = emailProperties;
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    @PostConstruct
    public void init() {
        if(emailProperties.getRequestUrl().isEmpty() || emailProperties.getAppKey().isEmpty()
                || emailProperties.getTemplateId().isEmpty()) {
            throw new RuntimeException("配置不能为空，请设置 app.email");
        }
    }

    public void sendEmail(String email, String code) {
        try {
            Map<String, Object> requestBody = buildRequestBody(email, code);
            ResponseEntity<String> response = restTemplate.postForEntity(emailProperties.getRequestUrl(), requestBody, String.class);
            if(response.getStatusCode().is2xxSuccessful()) {
                log.info("邮件发送成功，接收邮箱为：{}", email);
            }else {
                log.error("邮件发送失败");
                throw new RuntimeException("邮件发送失败");
            }
        }catch (JsonProcessingException e) {
            throw new RuntimeException("请求体序列化失败");
        }
    }

    private Map<String, Object> buildRequestBody(String email, String code) throws JsonProcessingException {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("app_key", emailProperties.getAppKey());
        requestBody.put("template_id", emailProperties.getTemplateId());
        requestBody.put("to", email);
        Map<String, Object> data = new HashMap<>();
        data.put("code", code);
        String jsonData = objectMapper.writeValueAsString(data);
        requestBody.put("data", jsonData);
        return requestBody;
    }
}